#include <QPainterPath>
#include <QRectF>
#include <QPolygon>
#include <QRegion>

#include <QDebug>
#include "cvimage.h"
#include "bizlogic/cvimagecache.h"
CVImage::CVImage(QWidget *parent) :
    QLabel(parent)
{

}

QUrl CVImage::getImageUrl()
{
    return this->mImageUrl;
}

void CVImage::setImageUrl(const QString &strUrl, bool isUserIcon)
{
    setImageUrl(QUrl(strUrl), isUserIcon);
}

void CVImage::setImageUrl(QUrl url, bool isUserIcon)
{
    this->mImageUrl = url;
    if (url.encodedPath().endsWith("defaultsmall.gif"))
    {
        QImage img(":images/user_default");
        setPixmap(QPixmap::fromImage(img));
    }
    else
    {
        CVImageCache *cache = CVImageCache::instance();
        if (cache->contains(url))
        {
            setPixmap(QPixmap::fromImage(cache->get(url)));
        }
        else
        {
            http = new CVImageHttp(url);
            if (!isUserIcon)
            {
                QImage *image = new QImage(":/images/no_photo");
                http->setDefaultImage(image);
            }
            connect(http, SIGNAL(handleImage(QPixmap)), this, SLOT(setPixmap(QPixmap)));
        }
    }

    if (isUserIcon)
    {
        QPainterPath path;
        QRectF rect = QRect(0, 0, 48, 48);
        path.addRoundedRect(rect, 3, 3);
        QPolygon polygon = path.toFillPolygon().toPolygon();
        QRegion region(polygon);
        setMask(region);
    }
}

void CVImage::mouseReleaseEvent(QMouseEvent *ev)
{
    emit clicked(this);
}

